/*

给定一个包含 n 个整数的数组 nums 和一个目标值 target，判断 nums 中是否存在四个元素 a，b，c 和 d ，使得 a + b + c + d 的值与 target 相等？找出所有满足条件且不重复的四元组。

注意：

答案中不可以包含重复的四元组。

示例：

给定数组 nums = [1, 0, -1, 0, -2, 2]，和 target = 0。

满足要求的四元组集合为：
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]
*/
function foreSum(nums, target) {
    nums.sort((a,b) => a - b);
    let result = [];
    for(let i = 0; i < nums.length; i++) {
        if(nums[i] > 0 && nums[i] > target) break;
        if( i > 0 && nums[i] == nums[i - 1]) continue;
        let left = i + 1;
        while(true){
            if(left + 2 >= nums.length) break;
            if(nums[i] + nums[left] > 0 && nums[i] + nums[left] > target) break;
            if(left > i + 1 && nums[left] == nums[left - 1]) {
                left++;
                continue;
            };
            let middle = left + 1;
            while(true) {
                if(middle >= nums.length - 1) break;
                if(nums[i] + nums[left] + nums[middle] > 0 && nums[i] + nums[left] + nums[middle] > target) break;
                if(middle > left + 1 && nums[middle] == nums[middle -1]) {
                    middle++;
                    continue;
                }
                let right = middle + 1;
                while(true) {
                    if(right >= nums.length) break;
                    if(right > middle + 1 && nums[right] == nums[right -1]) {
                        right++;
                        continue;
                    };
                    if(nums[i] + nums[left] + nums[middle] + nums[right] == target) {
                        result.push([nums[i], nums[left], nums[middle], nums[right]]);
                        break
                    }
                    right++;
                }
                middle++;
            }
            left++;
        }
    }
    return result;
}
// function foreSum(nums, target) {
//     let res=[]
//     let path=[]
//     nums.sort();
//     let backtrack = (start) => {

//     }
// }
function run() {
    let nums = [-500,-481,-480,-469,-437,-423,-408,-403,-397,-381,-379,-377,-353,-347,-337,-327,-313,-307,-299,-278,-265,-258,-235,-227,-225,-193,-192,-177,-176,-173,-170,-164,-162,-157,-147,-118,-115,-83,-64,-46,-36,-35,-11,0,0,33,40,51,54,74,93,101,104,105,112,112,116,129,133,146,152,157,158,166,177,183,186,220,263,273,320,328,332,356,357,363,372,397,399,420,422,429,433,451,464,484,485,498,499];
    let target = 2139;
    let result = foreSum(nums, target);
    return result;
}
module.exports = run;
